package br.com.filter;

import java.io.IOException;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;


@WebFilter(servletNames={"Faces Servlet"})
public class Filtro implements Filter{

	private EntityManagerFactory managerFactory;
	
	@Override
	public void destroy() {
		managerFactory.close();
	}


	public void init(FilterConfig filterConfig)
		throws ServletException{
		managerFactory = Persistence.createEntityManagerFactory("senai");
	}


	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain arg2) throws IOException, ServletException {
		
		EntityManager manager = managerFactory.createEntityManager();
		request.setAttribute("EntityManager", manager);
		
		
		EntityTransaction transaction = manager.getTransaction();
		transaction.begin();
		
		try{
			arg2.doFilter(request, response);
			if (transaction.isActive()) {
				transaction.commit();
				
			}
			
		}catch(Exception e){
			if (transaction.isActive()) {
				transaction.rollback();	
			} 
			e.printStackTrace();
			
		}
	}
	
}
